<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\FollowUpStoreRequest;
use App\Http\Requests\FollowUpUpdateRequest;
use App\Http\Requests\PatientOrRecordRequest;
use App\Models\MedicalFollowUp;
use App\Project\Filters\FollowUpFilter;
use App\Project\Transform;
use App\Transformers\FollowUpTransformer;
use App\Transformers\PreviousFollowWithPatientTransformer;
use App\Transformers\PreviousFollowWithRecordTransformer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use League\Fractal\Resource\Item;

class FollowUpController extends ApiController
{
    /**
     * @param \App\Http\Requests\FollowUpStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(FollowUpStoreRequest $request)
    {
        $input = (new FollowUpFilter($request))->input();

        $result = MedicalFollowUp::updateOrCreate(['record_id' => $input['record_id']], $input);

        return $this->response(['id' => $result['id']]);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = null;
        $id   = $request->get('id');

        if ($id > 0) {

            $data = MedicalFollowUp::findOrFail($id);
        } elseif ($record_id = $request->get('record_id')) {

            $data = MedicalFollowUp::where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失随诊ID，或者病历ID');
        }

        if (empty($data)) {
            throw (new ModelNotFoundException())->setModel(MedicalFollowUp::class);
        }

        return $this->item($data, new FollowUpTransformer($request, $this->fractal));
    }

    /**
     * @param \App\Http\Requests\FollowUpUpdateRequest $request
     * @param \App\Project\Transform                   $transform
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(FollowUpUpdateRequest $request, Transform $transform)
    {
        $where = [];

        if ($id = $request->input('id')) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $request->input('record_id');
        }

        $input = (new FollowUpFilter($request))->except(['id', 'record_id']);

        $input = $transform->setArray($input)->convertArrayToJson(
            [
                'blood_glucose', 'interval_evaluation', 'interval_symptom', 'medication', 'cn_medication', 'diet',
                'normal', 'thyroid', 'adrenal_gland'
            ]
        )->get();

        $result = MedicalFollowUp::where($where)->update($input);

        return $this->responseForUpdate($result);
    }

    /**
     * @param \App\Http\Requests\PatientOrRecordRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function previous(PatientOrRecordRequest $request)
    {
        $input = $request->only('patient_id', 'record_id');

        if ($input['record_id']) {

            return $this->previousWithRecordId($request, $input);
        }

        return $this->previousWithPatientId($request, $input['patient_id']);
    }

    /**
     * 通过病历ID 获取上一次病历的信息
     * @param \Illuminate\Http\Request $request
     * @param                          $input
     * @return \Illuminate\Http\JsonResponse
     */
    protected function previousWithRecordId(Request $request, $input)
    {
        $data = MedicalFollowUp::where(['record_id' => $input['record_id']])->first();

        if (empty($data)) {
            return $this->previousWithOutFollow($request, $input);
        }

        return $this->item($data, new FollowUpTransformer($request, $this->fractal));
    }

    /**
     * 用户在保存了 病历 但没有保存随诊时 使用的查询 信息方法
     * @param \Illuminate\Http\Request $request
     * @param                          $input
     * @return \Illuminate\Http\JsonResponse
     */
    protected function previousWithOutFollow(Request $request, $input)
    {
        try {
            return $this->onlyTrans(
                new PreviousFollowWithRecordTransformer($request, $this->fractal, $input['record_id'])
            );
        }catch (\InvalidArgumentException $exception) {
            return $this->setMessage($exception->getMessage())
                        ->setCode(40400)
                        ->hasNoData();
        }


    }

    /**
     * 使用患者ID值获取上次病历的信息
     * @param \Illuminate\Http\Request $request
     * @param                          $patient_id
     * @return \Illuminate\Http\JsonResponse
     */
    protected function previousWithPatientId(Request $request, $patient_id)
    {
        return $this->onlyTrans(
            new PreviousFollowWithPatientTransformer($request, $patient_id)
        );
    }
}
